// 创建一个ReactNative版本的MainScreen组件
import React, {useEffect} from 'react';
import {
  Button,
  Dimensions,
  Image,
  Text,
  TouchableNativeFeedback,
  TouchableOpacity,
  View,
  TouchableWithoutFeedback,
  ToastAndroid,
  DeviceEventEmitter,
  NativeModules,
} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';
import AutoSizingImage from '../components/AutoSizingImage';
import ImageConstants from '../resources/ImageConstants';
import ModalViewUtil from '../components/ModalViewUtil';
import ColorButton from '../components/ColorButton';
import Row from '../components/Row';
import {get, injectApi, post, rejectApi} from '../http/http';
import DeviceInfo from 'react-native-device-info';
import LoginView from '../views/LoginView';
import Colors from '../resources/Colors';
import ModifyPasswordView from '../views/ModifyPasswordView';
import config from '../config/config';
import {useResponsive} from 'react-native-responsive-hook';
import InnerLoginView from '../views/InnerLoginView';
import Config from 'react-native-config';
import moment from 'moment';
import {Dirs} from 'react-native-file-access';
const {HKVisionDeviceModule} = NativeModules;
const WIN_WIDTH = Dimensions.get('window').width;
export default function MainScreen({navigation}) {
  const [data, setData] = React.useState([]);
  const [imageIndex, setImageIndex] = React.useState(0);
  const [videos, setVideos] = React.useState([]);
  const [device, setDevice] = React.useState({});

  const injectChannel = channelId => {
    rejectApi('channel');
    injectApi('channel', (config: any) => {
      try {
        console.log('channel注入', config.headers, config.params);
        config.headers = {
          ...config.headers,
          channelId: channelId,
        };
        if (config.params) {
          config.params = {
            ...config.params,
            channelId: channelId,
          };
        }
        if (config.data) {
          config.data = {
            ...config.data,
            channelId: channelId,
          };
        }
      } catch (e) {
        console.log(e);
      }
    });
  };

  useEffect(() => {
    const loadData = async () => {
      const data = await get(
        '/assets/materialCabinetApi/api/findMaterialCabinetBindInfoApi?route=assets',
        {deviceId: config.DEVICE_ID},
      );
      if (!data.data) {
        navigation.navigate('DeviceBindScreen');
        return;
      }
      navigation.setOptions({
        headerLeft: () => (
          <Text
            style={{color: 'white', marginLeft: 10}}
            onPress={async () => {
              const date = moment().format('YYYY-MM-DDHH:mm:ss');
              // 截图
              // 创建一个临时图片文件地址，用于保存截图
              const filename = `${DeviceInfo.getUniqueIdSync()}_${date}.png`;
              const tempPath = `${Dirs.CacheDir}/${filename}`;
              console.log('tempPath:' + tempPath);
              // 截图
              await HKVisionDeviceModule.snapUVC(tempPath, 1, 9, 1920 * 1080);

              ToastAndroid.show('截图成功', ToastAndroid.SHORT);
              ModalViewUtil.showFromCenter(
                <View style={{width: WIN_WIDTH * 0.5, height: WIN_WIDTH}}>
                  <Image
                    source={{uri: 'file://' + tempPath}}
                    style={{width: '100%', height: '100%'}}
                  />
                </View>,
              );
            }}>
            {data.data.materialCabinetName} {data.data.materialCabinetNum}
          </Text>
        ),
      });
      injectChannel(data.data.channelId);
      setDevice(data.data);
      const result = await get(
        '/assets/materialCabinetApi/api/queryMaterialCabinetNewsApi?route=assets',
        {materialCabinetNum: data.data.materialCabinetNum},
      );
      setData(result.data.data);
      const data1 = await get(
        '/assets/materialCabinetNewsTypeApi/api/getMaterialCabinetNewsTypeByTypeNumApi',
        {typeNum: '000003'},
      );
      const data2 = await get(
        '/assets/materialCabinetNewsTypeApi/api/getMaterialCabinetNewsTypeByParentApi',
        {typeId: data1.data.typeId},
      );
      const data3 = await get(
        '/assets/materialCabinetNewsTypeApi/api/getMaterialCabinetNewsTypeVideoListApi',
        {typeId: data2.data[0].typeId},
      );
      setVideos(data3.data.data);
    };
    loadData();
  }, []);

  const unbindLock = () => {
    ModalViewUtil.showFromCenter(
      <LoginView
        userType={2}
        loginCancel={() => {
          ModalViewUtil.dismissBottomView();
        }}
        loginComplete={data => {
          ModalViewUtil.dismissBottomView();
          post(
            '/assets/materialCabinet/api/unBindingMaterialCabinet',
            {
              deviceId: config.DEVICE_ID,
              materialCabinetId: device.materialCabinetId,
            },
            true,
          )
            .then(res => {
              ToastAndroid.show('解绑成功', ToastAndroid.SHORT);
              navigation.navigate('DeviceBindScreen');
            })
            .catch(error => {
              ToastAndroid.show('解绑失败' + error.message, ToastAndroid.SHORT);
            });
        }}
      />,
    );
  };

  const modifyPassword = () => {
    ModalViewUtil.showFromCenter(
      <LoginView
        userType={2}
        loginCancel={() => {
          ModalViewUtil.dismissBottomView();
        }}
        loginComplete={data => {
          ModalViewUtil.dismissBottomView();
          setTimeout(() => {
            ModalViewUtil.showFromCenter(<ModifyPasswordView />);
          }, 350);
        }}
      />,
    );
  };
  const {wp, hp, rem} = useResponsive();
  let style = {
    width: '30%',
    marginLeft: '2.5%',
    marginTop: '1.5%',
    height: hp(14),
    backgroundColor: 'white',
    borderRadius: 5,
    overflow: 'hidden',
  };
  const uri = (data && data.length > 0 ? data[imageIndex].newsImg : '').replace(
    'sxt',
    't',
  );

  const Component = Config.ENV === 'dev' ? LoginView : InnerLoginView;

  // console.log('uri:', uri);
  return (
    <View
      style={{
        flex: 1,
        alignItems: 'stretch',
        backgroundColor: '#ebebec',
      }}>
      <ScrollView style={{flex: 1}}>
        <AutoSizingImage
          source={ImageConstants.ICON_TOP_BCG}
          width={'100%'}
          style={{width: '100%', flexDirection: 'row', padding: 0}}>
          <View
            style={{
              flex: 1,
              padding: wp(2),
            }}>
            <Text
              style={{fontSize: rem(15), fontWeight: 'bold', color: 'white'}}>
              新闻公告
            </Text>
            <View
              style={{
                width: '100%',
                flexDirection: 'row',
                alignItems: 'center',
                marginTop: 10,
                paddingTop: 10,
              }}>
              <Image
                source={uri ? {uri: uri} : ImageConstants.ICON_DEFAULT}
                defaultSource={ImageConstants.ICON_DEFAULT}
                style={{width: '30%', aspectRatio: 1.2}}
                resizeMode={'contain'}
              />
              <View style={{flex: 1, marginLeft: 10}}>
                {data &&
                  data.slice(0, 2).map((value, index) => {
                    return (
                      <TouchableNativeFeedback
                        onPress={() =>
                          navigation.navigate('CabnetNewsDetailPage', {
                            title: value.newsName,
                            html: value.newsContent,
                            img: value.newsImg.replace('sxt', 't'),
                          })
                        }>
                        <View
                          style={{
                            width: '100%',
                            padding: 15,
                            marginBottom: '2%',
                            justifyContent: 'center',
                            backgroundColor:
                              imageIndex === index
                                ? '#f2f2f266'
                                : 'transparent',
                          }}>
                          <Text style={{fontSize: 18}}>{value.newsName}</Text>
                          <Text
                            style={{fontSize: 14, marginTop: 10}}
                            numberOfLines={3}>
                            {value.newsAbstract}
                          </Text>
                        </View>
                      </TouchableNativeFeedback>
                    );
                  })}
              </View>
            </View>
          </View>
        </AutoSizingImage>

        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            paddingHorizontal: 15,
          }}>
          <AutoSizingImage
            source={ImageConstants.ICON_MIDDLE_BCG}
            width={'100%'}
            style={{marginTop: 15}}>
            <Image
              source={ImageConstants.ICON_MIDDLE_TEXT1}
              style={{marginTop: 20, marginLeft: 20}}
            />
            <Image
              source={ImageConstants.ICON_MIDDLE_TEXT2}
              style={{marginTop: 15, marginLeft: 20}}
            />
          </AutoSizingImage>
        </View>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            alignItems: 'center',
            paddingBottom: 15,
            justifyContent: 'space-between',
          }}>
          <TouchableOpacity
            style={{marginLeft: '2%'}}
            onPress={() => {
              ModalViewUtil.showFromCenter(
                <Component
                  userType={1}
                  loginCancel={() => {
                    ModalViewUtil.dismissBottomView();
                  }}
                  loginComplete={data => {
                    ModalViewUtil.dismissBottomView();
                    setTimeout(() => {
                      navigation.navigate('ReserveQueryScreen', {
                        materialCabinetId: device.materialCabinetId,
                      });
                    }, 500);
                  }}
                />,
              );
            }}>
            <AutoSizingImage
              source={ImageConstants.ICON_SAVE}
              width={wp(30)}
              style={{
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-around',
                height: hp(12),
              }}
              resizeMode={'stretch'}>
              <AutoSizingImage
                source={ImageConstants.ICON_TAKE_BTN_BCG}
                width={80}
                style={{justifyContent: 'center', alignItems: 'center'}}>
                <AutoSizingImage
                  source={ImageConstants.ICON_TAKE_BTN_IMG}
                  width={60}
                />
              </AutoSizingImage>
              <Text
                style={{
                  color: 'white',
                  fontSize: 25,
                  fontWeight: 'bold',
                  marginRight: 30,
                }}>
                查询预约
              </Text>
            </AutoSizingImage>
          </TouchableOpacity>
          <TouchableOpacity
            style={{marginLeft: '2%'}}
            onPress={() => {
              ModalViewUtil.showFromCenter(
                <Component
                  userType={1}
                  loginCancel={() => {
                    ModalViewUtil.dismissBottomView();
                  }}
                  loginComplete={data => {
                    ModalViewUtil.dismissBottomView();
                    setTimeout(() => {
                      navigation.navigate('CabinetProductsPage', {
                        materialCabinetId: device.materialCabinetId,
                      });
                    }, 500);
                  }}
                />,
              );
            }}>
            <AutoSizingImage
              source={ImageConstants.ICON_SAVE}
              width={wp(30)}
              resizeMode={'stretch'}
              style={{
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-around',
                height: hp(12),
              }}>
              <AutoSizingImage
                source={ImageConstants.ICON_TAKE_BTN_BCG}
                width={80}
                style={{justifyContent: 'center', alignItems: 'center'}}>
                <AutoSizingImage
                  source={ImageConstants.ICON_TAKE_BTN_IMG}
                  width={60}
                />
              </AutoSizingImage>
              <Text
                style={{
                  color: 'white',
                  fontSize: 40,
                  fontWeight: 'bold',
                  marginRight: 30,
                }}>
                取件
              </Text>
            </AutoSizingImage>
          </TouchableOpacity>
          <TouchableOpacity
            style={{marginHorizontal: '3%'}}
            onPress={() => {
              ModalViewUtil.showFromCenter(
                <Component
                  userType={1}
                  loginCancel={() => {
                    ModalViewUtil.dismissBottomView();
                  }}
                  loginComplete={data => {
                    ModalViewUtil.dismissBottomView();
                    setTimeout(() => {
                      navigation.navigate('BoxManagePage', {
                        materialCabinetId: device.materialCabinetId,
                      });
                    }, 500);
                  }}
                />,
              );
            }}>
            <AutoSizingImage
              source={ImageConstants.ICON_TAKE}
              width={wp(30)}
              resizeMode={'stretch'}
              style={{
                height: hp(12),
                alignItems: 'center',
                flexDirection: 'row',
                justifyContent: 'space-around',
              }}>
              <AutoSizingImage
                source={ImageConstants.ICON_SAVE_BTN_BCG}
                width={80}
                style={{justifyContent: 'center', alignItems: 'center'}}>
                <AutoSizingImage
                  source={ImageConstants.ICON_SAVE_BTN_IMG}
                  width={60}
                />
              </AutoSizingImage>
              <Text
                style={{
                  color: 'white',
                  fontSize: 40,
                  fontWeight: 'bold',
                  marginRight: 30,
                }}>
                存放
              </Text>
            </AutoSizingImage>
          </TouchableOpacity>
        </View>
        <AutoSizingImage
          source={ImageConstants.ICON_DOWN_BCG}
          width={wp(95)}
          style={{marginLeft: wp(2.5), marginTop: hp(1), height: hp(36)}}>
          <View
            style={{
              padding: 10,
            }}>
            <Text
              style={{
                fontSize: 24,
                fontWeight: 'bold',
                color: 'white',
                marginTop: 10,
              }}>
              实验室安全知识
            </Text>
            <Row style={{width: '100%', flexWrap: 'wrap', marginTop: 10}}>
              {videos.map(value => {
                return (
                  <TouchableWithoutFeedback
                    onPress={() =>
                      navigation.navigate('CabinetVideoPage', {data: value})
                    }>
                    <View style={style}>
                      <Image
                        defaultSource={ImageConstants.ICON_DEFAULT}
                        source={
                          value.newsImg.replace('sxt', 't')
                            ? {uri: value.newsImg.replace('sxt', 't')}
                            : ImageConstants.ICON_DEFAULT
                        }
                        resizeMode="stretch"
                        style={{width: '100%', height: hp(10)}}
                      />
                      <Text
                        style={{
                          color: '#333',
                          verticalAlign: 'middle',
                          flex: 1,
                          paddingHorizontal: 10,
                        }}
                        numberOfLines={2}>
                        {value.newsName}
                      </Text>
                    </View>
                  </TouchableWithoutFeedback>
                );
              })}
            </Row>
          </View>
        </AutoSizingImage>
      </ScrollView>
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          paddingHorizontal: 15,
          paddingVertical: 10,
          backgroundColor: 'rgba(87, 96, 118, 1)',
        }}>
        <TouchableOpacity
          onPress={() => DeviceEventEmitter.emit('checkUpdate')}>
          <Text
            style={{
              color: 'white',
              fontSize: wp(1.5),
              marginHorizontal: wp(1),
            }}>
            检查更新
          </Text>
        </TouchableOpacity>
        <View style={{flexDirection: 'row', alignItems: 'center'}}>
          <ColorButton
            containerStyle={{marginLeft: 15, paddingHorizontal: 10}}
            color={Colors.primaryColor}
            fontSize={rem(6)}
            height={25}
            onPress={unbindLock}>
            解绑
          </ColorButton>
          <ColorButton
            containerStyle={{marginLeft: 15, paddingHorizontal: 10}}
            color={Colors.primaryColor}
            fontSize={rem(6)}
            height={25}
            onPress={() => navigation.navigate('DeviceBindScreen')}>
            在线报修
          </ColorButton>
        </View>
      </View>
    </View>
  );
}
